//
//  TZWStatusPictureView.swift
//  Sinaweibotzw
//
//  Created by 檀志文 on 16/4/15.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

import UIKit

import SDWebImage

private let TZWStatusPictureViewCellMargin: CGFloat = 4

//cell 的最大列数 为3列， 列数使用整数
private let TZWStatusPictureViewMaxColumn = 3

//计算cell的高度
private let  TZWStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width - 2 * TZWStatusCellMargin - (CGFloat(TZWStatusPictureViewMaxColumn) - 1) * TZWStatusPictureViewCellMargin) / CGFloat(TZWStatusPictureViewMaxColumn)

class TZWStatusPictureView: UICollectionView {
    
    
    private let ReuseIdentifier = "ReuseIdentifier"
    var pictureURLs: [NSURL]? {
        didSet {
            // 当别人设置配图的url后,我们就来计算配图的高度
            let size = calcViewSize()
//           自己来约束大小，档cell 给pictureurls 之后计算出宽高，然后重新修改约束
            self.snp_updateConstraints { (make) -> Void in
//                make.size.equalTo(size)
                make.size.equalTo(size)
            }
            HMPrint("配图大小: \(size)")
            HMPrint("33333333\(pictureURLs)")
            self.reloadData()
        }
    }
    
    private func calcViewSize() ->CGSize{
//       1 collectionViewLayout
        layout.itemSize = CGSize(width: TZWStatusPictureViewItemWH, height: TZWStatusPictureViewItemWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
//        2 图片的数量
        let count = pictureURLs?.count ?? 0
        
//        3 没有图片
        if count == 0{
            return CGSizeZero
        }
//        1张图片
        if count == 1{
            var size = CGSize(width: TZWStatusPictureViewItemWH, height: TZWStatusPictureViewItemWH)
            // 返回图片本来的大小,拿到图片来获取大小
            // key: 图片的URL地址
            let url = pictureURLs?.first
            // 缓存图片有可能拿得到,也有可能那不到
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url?.absoluteString) {
                // 点坐标:像素 / 2, 在 SDWebimage 3.7.3以后
                size = image.size
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
            }
                // 如果图片太小,或太大,都处理一下
                if size.width < 40 {
                    size.width = 40
                }
                let screenWidth = UIScreen.mainScreen().bounds.width
                if size.width > screenWidth * 0.5 {
                    size.width = screenWidth * 0.5
                }
                
                layout.itemSize = size
                return size
        }
        layout.minimumLineSpacing = TZWStatusPictureViewCellMargin
    
        layout.minimumInteritemSpacing = TZWStatusPictureViewCellMargin
        
        var column = TZWStatusPictureViewMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        let row = (count + column - 1) / column
//      计算高度和宽度
        let width  = CGFloat(column) * TZWStatusPictureViewItemWH + (CGFloat(column) - 1) * TZWStatusPictureViewCellMargin
        let height = CGFloat(row) * TZWStatusPictureViewItemWH + (CGFloat(row) - 1) * TZWStatusPictureViewCellMargin
        
        return CGSize(width: width, height: height)
    }
    
    private var layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        // 设置数据源
        self.dataSource = self
        
        // 注册cell
        self.registerClass(TZWStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }

}

extension TZWStatusPictureView:UICollectionViewDataSource{
    /// 对应的section返回多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    
    /// 每个cell张什么样子
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 去缓存池中获取,如果缓存池中没有就会使用注册的cell来创建cell,并返回
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! TZWStatusPictureViewCell
        // 给cell设置URL
        cell.imageURL = pictureURLs![indexPath.item]
        
        return cell
    }
}

class TZWStatusPictureViewCell: UICollectionViewCell{
    var imageURL: NSURL? {
        didSet {
            bkgImageView.sd_setImageWithURL(imageURL!)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    private func prepareUI() {
        
        bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
        bkgImageView.clipsToBounds = true
        // 1.添加控件
        contentView.addSubview(bkgImageView)
        
        // 2.添加约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载
    /// 背景图片
    private lazy var bkgImageView: UIImageView = UIImageView()
}

